package com.b2wx.appcenter.plugin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.b2wx.appcenter.util.common.JedisUtil;

@SpringBootApplication(scanBasePackages= {"com.b2wx.appcenter.plugin","com.b2wx.appcenter.util.common"})
@EnableAutoConfiguration
@Controller
public class PluginApplication {
	public static void main(String[] args) {
		SpringApplication.run(PluginApplication.class, args);
		SocketServer.start();
	}
	@RequestMapping("/{pluginId}.pl/**")
	public void pluginProxy(HttpServletRequest request,HttpServletResponse resopnse,@PathVariable String pluginId) throws  IOException, ServletException {
		String key = request.getHeader("x-client-key");
		PluginClient client = PluginClient.pluginClientMap.get(key);
		if(client==null) {
			resopnse.setCharacterEncoding("utf-8");
			resopnse.sendError(500, "插件客户端("+key+")暂时无法提供服务，请稍后重试");
			JedisUtil.build().doAfterClose(jedis->{
				jedis.hdel("plugin.mapping",key);
			});
			return;
		}
		try {
			client.sendRequest(request, resopnse);
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new ServletException(e.getMessage());
		}
	}
}
